package org.deltaset.meta.internal;

import java.util.Locale;
import java.util.ResourceBundle;
import org.deltaset.meta.LabelResolver;
import org.deltaset.meta.MetaAction;
import org.deltaset.meta.MetaField;

/**
 *
 * @author dmakariev
 */
class LabelResolverImpl implements LabelResolver {

    @Override
    public String labelClass(final Class entityClass, final Locale currentLocale) {
        final String bundleName = entityClass.getName() + "Labels";
        final String key = "view.name";
        final String label = resolveLabel(bundleName, key, currentLocale);
        return "view.name".equals(label) ? entityClass.getSimpleName() : label;
    }

    @Override
    public String labelAction(final MetaAction action, final Locale currentLocale) {
        final String bundleName = action.getMethod().getDeclaringClass().getName() + "Labels";
        final String key = action.getMethodName();
        final String label = resolveLabel(bundleName, key, currentLocale);
        return label;
    }

    @Override
    public String labelField(final MetaField field, final Object owner, final Locale currentLocale) {
        //check for null
        if (owner instanceof Class) {
            final Class ownerClass = (Class) owner;
            final String bundleName = ownerClass.getName() + "Labels";
            final String key = field.getPropertyLabelKey();
            final String label = resolveLabel(bundleName, key, currentLocale);
            return label;
        } else if (owner instanceof MetaAction) {
            final MetaAction ownerAction = (MetaAction) owner;
            final String bundleName = ownerAction.getMethod().getDeclaringClass().getName() + "Labels";
            final String key = ownerAction.getMethodName() + "." + field.getPropertyLabelKey();
            final String label = resolveLabel(bundleName, key, currentLocale);
            return key.equals(label) ? field.getPropertyLabelKey() : label;
        }
        throw new IllegalArgumentException("ERROR not supported owner type = " + owner.getClass().getName());
    }

    private static String resolveLabel(final String resourceName, final String key, final Locale currentLocale) {
        final String label = getLabel(resourceName, key, currentLocale);
        return (null == label) ? key : label;
    }

    private static String getLabel(final String bundleName, final String key, final Locale currentLocale) {
        try {
            final ResourceBundle rb = ResourceBundle.getBundle(bundleName, currentLocale);
            final String label = rb.getString(key);
            return label;
        } catch (Exception ex) {
            return null;
        }
    }
}
